<?php

namespace App\Http\Controllers\Epay;

use App\Http\Controllers\Controller;
use App\Http\Requests\EpayOrderRequest;
use App\Models\Channel;
use App\Models\Order;
use App\Services\OrderService;
use Illuminate\Http\Request;
use Illuminate\Support\ViewErrorBag;
use Illuminate\Validation\ValidationException;

class OrdersController extends Controller
{
    public function submit(EpayOrderRequest $epayOrderRequest, OrderService $orderService)
    {
        $order = Order::query()->where('out_trade_no', $epayOrderRequest->input('out_trade_no'))->first();
        if (!is_null($order)) {
            $order->gateway = $epayOrderRequest->input('type');
            $order->save();
            return redirect()->route('pay', ['order' => $order->trade_no]);
        }
        $channel = Channel::random($epayOrderRequest->input('type'))[0] ?? [];
        if (!$channel) {
            return redirect()->route('error.message')->withErrors('暂无可用通道');
        }
        $order = $orderService->create([
            'client_id'       => $epayOrderRequest->input('pid'),
            'out_trade_no'    => $epayOrderRequest->input('out_trade_no'),
            'notify_url'      => $epayOrderRequest->input('notify_url'),
            'return_url'      => $epayOrderRequest->input('return_url'),
            'gateway'         => $epayOrderRequest->input('type'),
            'total_amount'    => $epayOrderRequest->input('money'),
            'from_url'        => $epayOrderRequest->header('referer'),
            'title'           => $epayOrderRequest->input('name'),
        ], $channel['id']);


        return redirect()->route('pay', ['order' => $order->trade_no]);
    }
}

//http://pay.test/epay/submit?pid=150000&type=wechat&out_trade_no=123213&notify_url=http://www.baidu.com&return_url=http://www.baidu.com&name=%E8%AE%A2%E5%8D%95&money=0.01&sign=123213
